import os
import secrets
from PIL import Image
from flask import Blueprint, render_template, url_for, flash, redirect, request, abort
from flask_login import current_user, login_required
from flask_blog.app import db
from flask_blog.models import Post
from flask_blog.forms import PostForm
from markdown import markdown
from docx import Document
from io import BytesIO

posts = Blueprint('posts', __name__)

# 新增：解析不同格式的文件内容
def parse_content_file(file, format):
    """根据文件和格式，读取并返回内容"""
    content = ""
    # 读取文件流
    file_stream = BytesIO(file.read())
    if format == 'txt' or format == 'markdown':
        # TXT/MD 直接读取文本
        content = file_stream.read().decode('utf-8')
    elif format == 'docx':
        # DOCX 用 python-docx 读取段落
        doc = Document(file_stream)
        content = '\n'.join([para.text for para in doc.paragraphs])
    file_stream.close()
    return content

@posts.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        # 优先用文件内容，若无则用手动输入内容
        if form.content_file.data:
            post_content = parse_content_file(
                form.content_file.data,
                form.content_format.data
            )
        else:
            post_content = form.content.data.strip()
        
        # 创建文章（包含格式字段）
        post = Post(
            title=form.title.data,
            content=post_content,
            content_format=form.content_format.data,  # 存储格式
            author=current_user
        )
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('main.home'))
    return render_template('create_post.html', title='New Post',
                           form=form, legend='New Post')

@posts.route("/post/<int:post_id>/update", methods=['GET', 'POST'])
@login_required
def update_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        # 处理内容（文件优先）
        if form.content_file.data:
            post.content = parse_content_file(
                form.content_file.data,
                form.content_format.data
            )
        elif form.content.data.strip():
            post.content = form.content.data.strip()
        # 更新标题和格式
        post.title = form.title.data
        post.content_format = form.content_format.data
        db.session.commit()
        flash('Your post has been updated!', 'success')
        return redirect(url_for('posts.post', post_id=post.id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content
        form.content_format.data = post.content_format  # 回显格式选择
    return render_template('create_post.html', title='Update Post',
                           form=form, legend='Update Post')

@posts.route("/post/<int:post_id>")
def post(post_id):
    post = Post.query.get_or_404(post_id)
    # 若为 Markdown 格式，后端转 HTML；其他格式直接保留原内容
    if post.content_format == 'markdown':
        post.rendered_content = markdown(post.content)
    else:
        post.rendered_content = post.content
    return render_template('post.html', title=post.title, post=post)

@posts.route("/post/<int:post_id>/delete", methods=['POST'])
@login_required
def delete_post(post_id):
    post = Post.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted!', 'success')
    return redirect(url_for('main.home'))
